import React, { useState, useEffect, useRef } from 'react';
import { DndContext, closestCenter, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { arrayMove, SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import Image from 'next/image';
import { GripVertical, Star, Plus, X, ImageUp } from 'lucide-react';
import axios from 'axios';
import 'nprogress/nprogress.css';
import NProgress from 'nprogress';
import message from '@/components/common/message';
import Popup from '@/components/admin/common/Popup';
import Pagination from '@/components/client/common/Pagination';

function SortableImage({ image, index, onRemove }) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: image.id });
  const style = { transform: CSS.Transform.toString(transform), transition, zIndex: isDragging ? 10 : 1, opacity: isDragging ? 0.6 : 1, cursor: 'grab', position: 'relative', background: '#fff', border: '1px solid #eee', borderRadius: 6, overflow: 'hidden' };
  return (
    <div ref={setNodeRef} style={style} {...attributes} {...listeners} className="flex flex-col items-center relative group w-full aspect-square">
      <Image src={image.url} alt={image.alt || ''} width={120} height={120} className="object-contain w-full aspect-square h-full" priority={true} />
      <div className="absolute left-1 top-1"> {image.is_primary === 0 && <Star size={18} color="white" title="主图" />} </div>
      <button className="absolute right-0.5 top-0.5 bg-white/95 rounded-full p-1 text-xs text-white w-6 h-6 grid items-center justify-center cursor-pointer" onClick={() => onRemove(image.id)} type="button" style={{ zIndex: 2 }} ><X style={{ width: '100%', height: '100%' }} color="black" /></button>
      <div className="absolute bottom-1 left-1/2 -translate-x-1/2 opacity-0 group-hover:opacity-100 transition"> <GripVertical size={18} /> </div>
    </div>
  );
}

function AddImageCard({ onAdd, disabled, onImageList }) {
  return (<div className={`flex flex-col items-center justify-center border border-dashed border-gray-300 rounded-xs bg-gray-50 hover:bg-gray-100 cursor-pointer aspect-square w-full relative`} onClick={disabled ? undefined : onImageList} tabIndex={0} >
    <Plus size={26} className="text-gray-400" /> <span className="text-xs text-gray-400">添加图片</span>
    <div onClick={onAdd} className='absolute right-0 bottom-0 bg-[#002FA7] p-0.5'> <ImageUp size={18} className="text-white" /> </div>
  </div>);
}

export default function SuperImageGallery({ value = [], handleChange, state = true, label, product_id, className }) {
  const [images, setImages] = useState(value);
  const [showImageList, setShowImageList] = useState(false);
  const [uploadedImages, setUploadedImages] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(1);
  const [limit] = useState(16);
  const inputRef = useRef(null);

  useEffect(() => {
    setImages(value);
  }, [value]);

  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 5 } })
  );

  const handleDragEnd = (event) => {
    const { active, over } = event;
    if (active.id !== over.id) {
      const oldIndex = images.findIndex(img => img.id === active.id);
      const newIndex = images.findIndex(img => img.id === over.id);
      const newImages = arrayMove(images, oldIndex, newIndex).map((img, idx) => ({ ...img, is_primary: idx === 0 ? 0 : 1, sort: idx + 1 }));
      setImages(newImages);
      handleChange && handleChange(newImages);
    }
  };

  const handleUpload = (url) => {
    const newImg = { id: Date.now() + Math.random(), url, alt: '', is_primary: images.length === 0 ? 0 : 1, sort: images.length + 1, product_id };
    const newImages = [...images.slice(0, images.length), newImg].map((img, idx) => ({ ...img, is_primary: idx === 0 ? 0 : 1, sort: idx + 1 })); setImages(newImages);
    handleChange && handleChange(newImages);
  };

  const handleRemove = (id) => {
    const newImages = images.filter(img => img.id !== id).map((img, idx) => ({ ...img, is_primary: idx === 0 ? 0 : 1, sort: idx + 1 }));
    setImages(newImages);
    handleChange && handleChange(newImages);
  };

  useEffect(() => {
    if (showImageList) {
      const fetchData = async () => {
        try {
          const res = await fetch(`/api/admin/files?page=${currentPage}&pageSize=${limit}&type=image`, { method: 'GET', credentials: 'include' });
          const data = await res.json();
          setUploadedImages(data.files || []);
          setTotal(data.total);
        } catch (error) {
          message.error('获取图片列表失败');
        }
      };
      fetchData();
    }
  }, [currentPage, showImageList, limit]);

  const handleImageChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        const formData = new FormData();
        formData.append('file', file);
        NProgress.start();
        axios.post('/api/admin/files', formData, {
          onUploadProgress: (event) => {
            if (event.total) {
              const percent = Math.round((event.loaded / event.total) * 100);
              NProgress.set(percent / 100);
            }
          }
        }).then(res => {
          if (res.data.url) {
            message.success('上传成功！');
            handleUpload(res.data.url);
          }
          NProgress.done();
        }).catch(() => {
          message.error('上传失败');
          NProgress.done();
        });
      };
      reader.readAsDataURL(file);
    }
  };

  const handleImageClick = (e) => {
    if (state) {
      e.stopPropagation();
      inputRef.current.click();
    }
  };

  const handleImageList = (e) => {
    e.stopPropagation();
    setCurrentPage(1);
    setShowImageList(true);
  }

  const selectImage = (url) => {
    handleUpload(url);
    setShowImageList(false);
  };

  return (
    <div className={`flex flex-col gap-2 my-4 ${className || ''}`}>
      {label && <label className="form-label text-sm text-gray-600 mb-2">{label}：</label>}
      <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
        <SortableContext items={images.map(img => img.id)} strategy={verticalListSortingStrategy}>
          <div className="grid grid-cols-10 gap-3">
            {images.map((img, idx) => (<SortableImage key={img.id} image={img} index={idx} onRemove={handleRemove} />))}
            <AddImageCard onAdd={handleImageClick} disabled={!state} onImageList={handleImageList} />
          </div>
        </SortableContext>
      </DndContext>

      <Popup isOpen={showImageList} onClose={() => setShowImageList(false)}>
        <div className="grid grid-cols-2 md:grid-cols-8 gap-6"> {uploadedImages.length > 0 ? uploadedImages.map(({ url }) => (<div key={url} onClick={() => selectImage(url)} className="cursor-pointer border border-gray-300 rounded-xs bg-white"> <Image width={720} height={720} src={url} alt="uploaded" className="w-full aspect-square object-contain rounded-none" /> </div>)) : <> {Array.from({ length: limit }).map((_, i) => (<div key={i} className="skeleton w-full aspect-square"></div>))} </>} </div>
        <Pagination page={currentPage} total={total} limit={limit} leftDisabled={currentPage === 1} rightDisabled={currentPage === Math.ceil(total / limit)} leftOnClick={() => setCurrentPage(p => Math.max(1, p - 1))} rightOnClick={() => setCurrentPage(p => Math.min(Math.ceil(total / limit), p + 1))} />
      </Popup>
      <input ref={inputRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handleImageChange} />
    </div>
  );
}